package com.uzai.console.web.tb.tbpunishorder;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.component.excel.listener.ExcelListener;
import com.uzai.console.component.excel.template.TbPunishOrderExcelDemo;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.module.merchant.MerchantSetDeviceTypeDto;
import com.uzai.console.dto.tb.tbpunishorder.*;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.dto.wechatprivate.wxcontacts.ExportResultDto;
import com.uzai.console.dto.wechatprivate.wxcontacts.WxContactsQuery;
import com.uzai.console.entity.TbToken;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.service.tb.tbpunishorder.TbPunishOrderService;
import com.uzai.console.service.tb.tbpunishorder.TbPunishOrderSyncService;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.module.merchant.MerchantDeviceTypeVo;
import com.uzai.console.vo.tb.tbpunishorder.TbPunishOrderInfoVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 淘宝处罚订单
 * @author liuqi
 * @date 2021年08月16日 15:11
 */
@Api(value = "淘宝处罚订单",tags = "淘宝|淘宝处罚订单")
@ApiSort(9)
@RestController
public class TbPunishOrderController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(TbPunishOrderController.class);

    @Autowired
    private TbPunishOrderService tbPunishOrderService;
    @Autowired
    private TbPunishOrderSyncService tbPunishOrdersyncService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbTokenMapper tbTokenMapper;

    @ApiOperation(value = "分页查询淘宝处罚订单列表", notes = "分页查询淘宝处罚订单列表", response = TbPunishOrderInfoVo.class)
    @ApiOperationSupport(order = 1)
    @PostMapping("/tbPunishOrder/findTbPunishOrderList")
    public Object findTbPunishOrderList(@RequestBody TbPunishOrderQuery tbPunishOrderQuery){
        return tbPunishOrderService.findTbPunishOrderList(tbPunishOrderQuery);
    }

    @SystemLogType(model = SystemModelEnum.TbPunishOrder, type = OperationTypeEnum.DOWNLOAD)
    @ApiOperation(value = "下载淘宝处罚订单", notes = "下载淘宝处罚订单")
    @ApiOperationSupport(order = 2)
    @PostMapping("/tbPunishOrder/downloadTbPunishOrder")
    public Object downloadTbPunishOrder(@RequestBody TbPunishOrderDownLoadDto tbPunishOrderDownLoadDto){

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TB_DOWNLOAD_PUNISH_ORDER_OPE, tbPunishOrderDownLoadDto.getMerId()));

        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"5分钟内只允许一次下载请求");
        }

        tbPunishOrderService.downloadTbPunishOrder(tbPunishOrderDownLoadDto);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.TB_DOWNLOAD_PUNISH_ORDER_OPE, tbPunishOrderDownLoadDto.getMerId()),tbPunishOrderDownLoadDto.getMerId()+"",5, TimeUnit.MINUTES);

        return true;
    }

    @SystemLogType(model = SystemModelEnum.TbPunishOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "扣款淘宝处罚订单", notes = "扣款淘宝处罚订单")
    @ApiOperationSupport(order = 3)
    @PostMapping("/tbPunishOrder/updateTbPunishOrder")
    public Object updateTbPunishOrder(@RequestBody TbPunishOrderIdDto tbPunishOrderIdDto){
        tbPunishOrderService.takeOffTbPunishOrder(tbPunishOrderIdDto);
        return true;
    }

    @SystemLogType(model = SystemModelEnum.TbPunishOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "批量扣款淘宝处罚订单", notes = "批量扣款淘宝处罚订单")
    @ApiOperationSupport(order = 3)
    @PostMapping("/tbPunishOrder/batchTakeOffTbPunishOrder")
    public Object batchTakeOffTbPunishOrder(@RequestBody TbPunishOrderIdListDto tbPunishOrderIdListDto){
        tbPunishOrdersyncService.batchTakeOffTbPunishOrder(tbPunishOrderIdListDto);
        return true;
    }

    @ApiOperation(value = "查询联盟账号下拉列表", notes = "查询联盟账号下拉列表", response = SelectKeyVo.class)
    @ApiOperationSupport(order = 4)
    @PostMapping("/tbPunishOrder/findTbTokenSelectList")
    public Object findTbTokenSelectList(){
        List<SelectKeyVo> selectIdVoList = new ArrayList<>();
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(getLoginInfo().getMerId());
        List<TbToken> tbTokenList = tbTokenMapper.findByList(tbTokenQuery);
        if(tbTokenList != null){
            for (TbToken tbToken : tbTokenList){
                SelectKeyVo selectKeyVo = new SelectKeyVo();
                selectKeyVo.setKey(String.valueOf(tbToken.getId()));
                selectKeyVo.setValue(tbToken.getUserName());
                selectIdVoList.add(selectKeyVo);
            }
        }
        return selectIdVoList;
    }

    @ApiOperation(value = "上传处罚订单文件", notes = "上传处罚订单文件")
    @ApiOperationSupport(order = 5)
    @PostMapping("/tbPunishOrder/uploadTbPunishOrderFile")
    public Object uploadTbPunishOrderFile(MultipartFile file, TbPunishOrderUpLoadDto tbPunishOrderUpLoadDto){

        //文件上传不能拦截参数赋值
        tbPunishOrderUpLoadDto.setMerId(getLoginInfo().getMerId());
        tbPunishOrderUpLoadDto.setLoginToken(getLoginInfo().getLoginToken());

        if(tbPunishOrderUpLoadDto.getSettleMonth() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入结算月份");
        }

        if(tbPunishOrderUpLoadDto.getViolationType() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入处罚类型");
        }

        if(file == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "文件不存在");
        }

        try {

            ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.CSV;

            if(file.getOriginalFilename().endsWith(".csv")){
                excelTypeEnum = ExcelTypeEnum.CSV;
            }else if(file.getOriginalFilename().endsWith(".xls")){
                excelTypeEnum = ExcelTypeEnum.XLS;
            }else{
                excelTypeEnum = ExcelTypeEnum.XLSX;
            }

            EasyExcel.read(file.getInputStream(), TbPunishOrderExcelDemo.class, new ExcelListener(p->{
                //保存逻辑（可封装一个普通的sevice）p-为我们执行函数时传入的list
                tbPunishOrderService.uploadTbPunishOrderFile(p, tbPunishOrderUpLoadDto);
            })).excelType(excelTypeEnum).sheet().doRead();
        } catch (IOException e) {
            logger.error("上传处罚订单失败:error={}", e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        }
        return true;
    }

    @ApiOperation(value = "淘宝处罚订单查询结果导出文件前检验接口", notes = "淘宝处罚订单查询结果导出文件前检验接口", response = ExportAmountVo.class)
    @ApiOperationSupport(order = 6)
    @PostMapping("/tbPunishOrder/getExportAmount")
    public Object getExportAmount(@RequestBody TbPunishOrderQuery tbPunishOrderQuery){
        return tbPunishOrderService.getExportAmount(tbPunishOrderQuery);
    }

    @SystemLogType(model = SystemModelEnum.TbPunishOrder, type = OperationTypeEnum.EXPORT)
    @ApiOperation(value = "淘宝处罚订单查询结果导出文件", notes = "淘宝处罚订单查询结果导出文件")
    @ApiOperationSupport(order = 7)
    @PostMapping("/tbPunishOrder/exportByQeuryResult")
    public Object exportByQeuryResult(@RequestBody TbPunishOrderExportResultDto tbPunishOrderExportResultDto){
        tbPunishOrderService.exportByQeuryResult(tbPunishOrderExportResultDto);
        return true;
    }


    @ApiOperation(value = "查询淘宝处罚订单是否自动扣款", notes = "查询淘宝处罚订单是否自动扣款", response = MerchantDeviceTypeVo.class)
    @PostMapping("/tbPunishOrder/findAutoChargeback")
    public Object findAutoChargeback(){
        return tbPunishOrderService.findAutoChargeback(getLoginInfo().getMerId());
    }

    @SystemLogType(model = SystemModelEnum.TbPunishOrder, type = OperationTypeEnum.UPDATE)
    @ApiOperation(value = "修改淘宝处罚订单自动扣款", notes = "修改淘宝处罚订单自动扣款", response = Boolean.class)
    @PostMapping("/merchant/updateAutoChargeback")
    public Object updateAutoChargeback(@RequestBody TbPunishOrderAutoChargebackDto tbPunishOrderAutoChargebackDto){
        tbPunishOrderService.updateAutoChargeback(tbPunishOrderAutoChargebackDto);
        return true;
    }
}
